package org.simplecrm.repository.user;

import org.simplecrm.domain.user.User;
import org.simplecrm.domain.usergroup.UserGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Implementation for JDBC database.
 */
@Repository("userDAO")
public class UserJdbcDAO implements UserDAO {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserJdbcDAO.class);

    private static final String SELECT_WHERE_NAME = "SELECT * FROM security_users WHERE login=?";

    private DataSource ds;

    @Autowired
    public UserJdbcDAO(DataSource ds) {
        this.ds = ds;
    }

    @Override
    public User getUserByName(String username) {

        User securityUser = null;

        try (Connection con = ds.getConnection();
             PreparedStatement statement = con.prepareStatement(SELECT_WHERE_NAME,
                     ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_UPDATABLE)) {

            statement.setString(1, username);

            try (ResultSet resultset = statement.executeQuery()) {

                while (resultset.next()) {

                    Integer id = resultset.getInt(U_ID_FIELD);
                    String password = resultset.getString(U_PASSWORD_FIELD);

                    UserGroup userGroup = null; //TODO: temp. Have UsergroupDAO be injected and used?
                    securityUser = new User(id, username, password, userGroup);
                }
            }
        } catch (SQLException ex) {
            LOGGER.error(ex.toString(), ex);
        }
        return securityUser;
    }

}
